package com.jmkj.service.wechat.controller;

import com.jmkj.service.wechat.entity.WechatTask;
import com.jmkj.service.wechat.entity.WechatWorker;
import com.jmkj.service.wechat.repository.WechatTaskRepository;
import com.jmkj.service.wechat.repository.WechatWorkerRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
@RequestMapping(path = "/wechat")
@Slf4j
public class WechatWorkController {
    @Autowired
    private WechatTaskRepository wechatTaskRepository;

    @Autowired
    private WechatWorkerRepository wechatWorkerRepository;

    /**
     * 添加一个任务，并初始化状态
     * @param phoneNum， 待添加用户手机号
     * @param message， 待添加请求的信息
     * @return
     */
    @GetMapping(path = "/addTask")
    public synchronized Boolean addTask(@RequestParam("phoneNum") Long phoneNum,
                           @RequestParam("message") String message){
        WechatTask task = new WechatTask();

        task.setPhoneNum(phoneNum);
        task.setMessage(message);
        task.setTaskLaunched(false);
        task.setWorkerId(0L);
        task.setTaskLaunched(false);

        log.info("insert task:{}", task);
        wechatTaskRepository.save(task);

        return true;
    }

    /**
     * 获取一个任务
     * @param workerId
     * @return
     */
    @GetMapping(path = "/getTask")
    public synchronized WechatTask getTask(@RequestParam("workerId")Long workerId){
        //取一个未分配的任务
        WechatTask task = wechatTaskRepository.findFirst1ByTaskLaunched(false);
        if(task == null){
            task = new WechatTask();
        }else{
            //更新任务状态
            task.setWorkerId(workerId);
            task.setTaskLaunched(true);
            task.setTaskCompleted(false);

            //保存任务
            wechatTaskRepository.save(task);

            Optional<WechatWorker> workerOptional = wechatWorkerRepository.findById(workerId);
            if(workerOptional.isPresent()){
                WechatWorker worker = workerOptional.get();
                worker.setTotalTaskCnt(worker.getTotalTaskCnt() + 1);
                wechatWorkerRepository.save(worker);
            }
        }

        return task;
    }

    /**
     * 关闭任务
     * @param workerId, 工作手机号
     * @param phoneNum,  被添加的用户手机号
     * @param success,  是否成功
     * @param errorMsg, 错误信息
     * @return
     */
    @GetMapping(path = "/closeTask")
    public synchronized Boolean closeTask(@RequestParam("workerId")Long workerId,
                             @RequestParam("phoneNum")Long phoneNum,
                             @RequestParam("success")Boolean success,
                             @RequestParam("errorMsg")String errorMsg){
        Optional<WechatWorker> workerOptional = wechatWorkerRepository.findById(workerId);
        WechatTask task = wechatTaskRepository.findAByPhoneNum(phoneNum);

        if(task != null){
            task.setTaskCompleted(success);
            task.setTaskLaunched(true);
        }else{
            task = new WechatTask();
            task.setWorkerId(workerId);
            task.setPhoneNum(phoneNum);
            task.setTaskCompleted(success);
            task.setTaskLaunched(true);
            task.setErrorMsg(errorMsg);
        }
        wechatTaskRepository.save(task);

        if(workerOptional.isPresent() && success){
            WechatWorker worker = workerOptional.get();
            worker.setSuccessTaskCnt(worker.getSuccessTaskCnt() + 1);
            wechatWorkerRepository.save(worker);
        }
        return true;
    }

    @GetMapping(path = "/addWorker")
    public synchronized Boolean addWorker(@RequestParam("workerId")Long workerId,
                             @RequestParam("wechatId")String wechatId){
        Optional<WechatWorker> worker = wechatWorkerRepository.findById(workerId);
        if(worker.isPresent()){
            log.warn("worker {} already exist!", workerId);
            return false;
        }else{
            WechatWorker w = new WechatWorker();
            w.setWorkerId(workerId);
            w.setWechatId(wechatId);
            w.setSuccessTaskCnt(0);
            w.setTotalTaskCnt(0);
            wechatWorkerRepository.save(w);
            return true;
        }
    }
}
